<template>
  <el-form :model="data" ref="form" class="form">
    <!-- 选中了销售属性 -->
    <div v-for="(sku, skuIndex) in data.skuList" :key="skuIndex" class="skuBox">
      <!-- 属性组合名称 -->
      <div class="combineBox">
        <span class="title">SKU信息：</span>
        <span
          class="combineName"
          v-for="(skuAttr, skuAttrIndex) in sku.skuAttrList"
          :key="skuAttrIndex"
        >
          <el-tag>{{ skuAttr.attrName }} : {{ skuAttr.attrValue }}</el-tag>
        </span>
      </div>

      <div class="detail">
        <!-- 每个属性组合下的标题、价格和库存 -->
        <el-form-item
          :prop="'skuList.' + skuIndex + '.title'"
          label="商品标题"
          :rules="rules.title"
          :label-width="formLabelWidth"
        >
          <el-input v-model="sku.title" placeholder="请输入商品标题"></el-input>
        </el-form-item>
        <el-form-item
          :prop="'skuList.' + skuIndex + '.price'"
          label="商品价格"
          :rules="rules.price"
          :label-width="formLabelWidth"
        >
          <el-input v-model="sku.price" placeholder="请输入商品价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          :prop="'skuList.' + skuIndex + '.stockNum'"
          label="商品库存"
          :rules="rules.stockNum"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="sku.stockNum"
            placeholder="请输入库存数量"
          ></el-input>
        </el-form-item>

        <!-- 图片列表及活动设置 -->
        <div class="otherBox">
          <el-collapse>
            <el-collapse-item title="图片列表及活动设置">
              <SpuUpload
                ref="spuUpload"
                :meta="{ index: skuIndex }"
                :showSelectBtn="true"
                :imageList="sku.skuImageList"
                @uploadRemove="uploadRemove"
                @uploadSuccess="uploadSuccess"
              />
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </el-form>
</template>

<script>
import ruleUtils from "@/utils/ruleUtils";
import productFormMixins from "@/views/base/productForm";
import jsonUtils from "@/utils/jsonUtils";

import SpuUpload from "./components/spuUpload.vue";

export default {
  name: "spuUpdateSpuForm",
  mixins: [productFormMixins],
  props: ["spuInfo"],
  components: {
    SpuUpload,
  },
  data() {
    return {
      init: {
        hasSaleAttrs: false,
        skuList: [],
      },
      data: {
        hasSaleAttrs: false,
        skuList: [],
      },
      // 商品sku列表
      combinedSaleAttrList: [],
      rules: {
        title: [
          {
            required: true,
            message: "请输入商品标题",
            trigger: "blur",
          },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 之间",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
          {
            validator: ruleUtils.validateMoney,
            trigger: "blur",
          },
        ],
        stockNum: [
          {
            required: true,
            message: "请输入库存数量",
            trigger: "blur",
          },
          {
            validator: ruleUtils.validatePositiveInteger,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    uploadRemove(meta, image) {
      this.data.skuList.forEach((sku, skuIndex) => {
        if (meta.index == skuIndex) {
          sku.skuImageList = sku.skuImageList.filter(
            (item) => item.sn !== image.sn
          );
        }
      });
    },
    uploadSuccess(meta, image) {
      this.data.skuList.forEach((sku, skuIndex) => {
        if (meta.index == skuIndex) {
          sku.skuImageList.push(image);
        }
      });
    },
    // spu 图片删除
    spuImagesRemove(data) {
      var image = jsonUtils.deepCopy(data);
      this.data.skuList.forEach((sku, skuIndex) => {
        sku.skuImageList = sku.skuImageList.filter(
          (item) => item.sn !== image.sn
        );
      });
    },
    // spu 图片添加
    spuImagesAdd(data, postion) {
      var image = jsonUtils.deepCopy(data);
      image.deletable = false;
      this.data.skuList.forEach((sku, skuIndex) => {
        sku.skuImageList.splice(postion - 1, 0, image);
      });
    },
    initData() {
      if (this.spuInfo.skuInfos) {
        this.data.skuList = jsonUtils.deepCopy(this.spuInfo.skuInfos);
        this.data.hasSaleAttrs = this.spuInfo.hasSaleAttrs;

        // 设置默认图片编号
        this.$nextTick(() => {
          this.data.skuList.forEach((sku, skuIndex) => {
            this.$refs.spuUpload[skuIndex].setDefaultImageSn(
              sku.defaultSkuImageSn
            );
          });
        });
      } else {
        this.data.skuList.push({
          title: "",
          price: null,
          stockNum: null,
          skuImageList: [],
          skuAttrList: [],
        });
        this.data.hasSaleAttrs = false;
      }
    },
    // 重新刷新数据
    refreshData(data, spuImages) {
      var combinedSaleAttrList = data.combinedSaleAttrList;
      this.data.skuList = [];

      // 没有选中属性
      if (combinedSaleAttrList.length == 0) {
        this.data.skuList.push({
          title: "",
          price: null,
          stockNum: null,
          skuImageList: jsonUtils.deepCopy(spuImages),
          skuAttrList: [],
        });
        this.data.hasSaleAttrs = false;
      }

      // 选中了属性
      if (combinedSaleAttrList.length > 0) {
        combinedSaleAttrList.forEach((skuAttrList) => {
          this.data.skuList.push({
            title: "",
            price: null,
            stockNum: null,
            skuImageList: jsonUtils.deepCopy(spuImages),
            skuAttrList: skuAttrList,
          });
        });
        this.data.hasSaleAttrs = true;
      }
    },
    // 获取数据
    getData() {
      var skuList = jsonUtils.deepCopy(this.data.skuList);

      // 过滤掉没有选中的
      skuList.forEach((sku) => {
        sku.skuImageList = sku.skuImageList.filter(
          (skuImage) => skuImage.selected == true
        );
      });

      // 设置默认图片
      var hasDefault = [];
      skuList.forEach((sku, skuIndex) => {
        hasDefault.push(false);

        var selectedImageSn = this.$refs.spuUpload[skuIndex].selectedImageSn;
        sku.skuImageList.forEach((skuImage) => {
          skuImage.isDefault = 0;
          if (skuImage.sn == selectedImageSn) {
            hasDefault[skuIndex] = true;
            skuImage.isDefault = 1;
          }
        });
      });

      // 没有设置，默认选择第一个
      skuList.forEach((sku, skuIndex) => {
        if (!hasDefault[skuIndex] && sku.skuImageList.length > 0) {
          sku.skuImageList[0].isDefault = 1;
        }
      });

      // 设置图片排序
      skuList.forEach((sku, skuIndex) => {
        var initSort = 100;
        sku.skuImageList.forEach((image) => {
          if (image.isDefault == 1) {
            image.sort = 100;
          } else {
            image.sort = ++initSort;
          }
        });
      });

      return skuList;
    },
    // 获取预览数据
    getPreviewData() {
      var skuList = jsonUtils.deepCopy(this.getData());
      var newSkuList = [];
      skuList.forEach((sku) => {
        newSkuList.push(sku);
        newSkuList.push(sku);
      });
      return {
        hasSaleAttrs: this.data.hasSaleAttrs,
        skuList: newSkuList,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.form {
  overflow: auto;
  height: 60vh;
  padding-right: 20px;
  .skuBox {
    margin-bottom: 40px;
    .combineBox {
      margin-bottom: 20px;
      .title {
        color: #409eff;
      }
      .combineName {
        margin-bottom: 5px;
        margin-right: 10px;
      }
      .combineSingleName {
        .el-tag {
          margin-right: 5px;
        }
      }
    }
    .detail {
      border: 1px solid #efefef;
      padding: 20px 20px 10px 20px;
      .otherBox {
        :deep(.el-collapse) {
          border: none;
        }
        :deep(.el-collapse-item__header) {
          justify-content: flex-end;
          border-bottom: none;
          .el-collapse-item__arrow {
            margin: 0px 0px 0px 10px;
          }
        }
        :deep(.el-collapse-item__wrap) {
          border-bottom: none;
        }
      }
    }
  }
}
</style>